package com.pomelo.base.core.web;

import javax.servlet.http.HttpServletRequest;

import com.pomelo.base.core.bean.BizException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pomelo.base.core.bean.ResultBean;

/**
 * 全局异常
 *
 * @author biankudingcha
 * @date: 2021-09-26
 * @since 0.5.0
 */
@ControllerAdvice public class GlobalExceptionHandler {

    /**
     * 日志对象
     */
    private static Log LOGGER = LogFactory.getLog(GlobalExceptionHandler.class);

    private final String ERROR_MSG = "系统异常，请联系管理员";

    /**
     * 基于@ExceptionHandler异常处理@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
     *
     * @throws Exception
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody public ResultBean handleException(HttpServletRequest request,
        Exception ex) {
        ResultBean result = new ResultBean();
        LOGGER.error(ERROR_MSG, ex);
        result.setMsg(ERROR_MSG);
        result.setCode(ResultBean.EXCEPTION_CODE);
        result.setSuccess(false);
        return result;
    }

    @ExceptionHandler(BizException.class)
    @ResponseBody
    public ResultBean handleException2(HttpServletRequest request, Exception ex) {
        ResultBean result = new ResultBean();
        LOGGER.error(ex.getMessage(), ex);
        result.setMsg(ex.getMessage());
        result.setCode(ResultBean.EXCEPTION_CODE);
        result.setSuccess(false);
        return result;
    }

}
